package com.dina.saas.peccancy.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.httpclient.util.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.dina.saas.peccancy.domain.Params;
import com.dina.saas.peccancy.domain.ResponsePeccMsg;

public class NanJingTask extends Task {

	private Parser parser = new NanJingParser();
	private Logger logger = Logger.getLogger(NanJingTask.class);

	public ResponsePeccMsg execute() {
		ResponsePeccMsg peccMsg = new ResponsePeccMsg("listPecc", 1, "");
		HttpClient httpclient = new DefaultHttpClient();
		CookieStore cookieStore = new BasicCookieStore();
		HttpContext httpContext = new BasicHttpContext();
		httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
		httpclient.getParams().setIntParameter("http.socket.timeout", 5000);
		HttpPost httppost = new HttpPost(this.getEncodingUrl());
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("newsearch", "1"));
		params.add(new BasicNameValuePair("imageButton.x", "25"));
		params.add(new BasicNameValuePair("imageButton.y", "12"));
		Params requestParams = requestMsg.getParams();
		if (params != null) {
			params.add(new BasicNameValuePair("chexing", requestParams
					.getVehicleType()));
			params.add(new BasicNameValuePair("begindate", requestParams
					.getStartDate()));
			params.add(new BasicNameValuePair("enddate", requestParams
					.getEndDate()));
			params.add(new BasicNameValuePair("keywords", requestParams
					.getBrandId().substring(0, 2)));
			params.add(new BasicNameValuePair("keywords2", requestParams
					.getBrandId().substring(2)));
			params.add(new BasicNameValuePair("fdjh", requestParams
					.getEngineNo()));
		}
		try {
			httppost.setHeader("Content-Type",
					"application/x-www-form-urlencoded");
			httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse response = httpclient.execute(httppost, httpContext);
			if (response.getStatusLine().getStatusCode() == 200) {// 如果状态码为200,就是正常返回
				HttpEntity ent = response.getEntity();
				this.result = EntityUtils.toString(response.getEntity());
				peccMsg = parser.parseAll(result);
				if (peccMsg.getResult() == 1) {
					logger.info("["+requestParams.getBrandId()
							+" " +requestParams.getEngineNo()
							+"]"+Constants.NO_RESULT_ERROR);
					peccMsg.setResultNote(Constants.NO_RESULT_ERROR);
					return peccMsg;
				}
				int num = 1;
				while (peccMsg.getTotalRecordNum() > peccMsg.getDetail()
						.getPeccancyArray().size()) {
					if (ent != null)
						ent.consumeContent();
					String url = this.getEncodingUrl()
							+ "?pid="
							+ (this.getRequestMsg().getParams().getPageNo() + (++num));
					HttpGet httpGet = new HttpGet(url);
					httpGet.setHeader("Content-Type",
							"application/x-www-form-urlencoded");
					HttpResponse httpResponse = httpclient.execute(httpGet,
							httpContext);
					int httpCode = httpResponse.getStatusLine().getStatusCode();
					if (httpCode == HttpURLConnection.HTTP_OK) {
						result = EntityUtils.toString(httpResponse.getEntity());
						parser.parsePeccs(peccMsg, result);
					} else {
						logger.error("URL[ " + url + " ]httpCode return is  "
								+ httpCode + " not OK,pls check the url!");
						peccMsg.setResultNote(Constants.HTTP_ERROR);
						return peccMsg;
					}
				}
			} else {
				logger.error("URL[ " + url + " ]httpCode return is  "
						+ response.getStatusLine().getStatusCode() + " not OK,pls check the url!");
				peccMsg.setResultNote(Constants.HTTP_ERROR);
				return peccMsg;
			}
			Integer totalRecord = peccMsg.getTotalRecordNum();
			Integer start = requestParams.getPagesize()
					* requestParams.getPageNo();
			Integer end = (start + requestParams.getPagesize()) > totalRecord ? totalRecord
					: (start + requestParams.getPagesize());
			if (start >= end) {
				peccMsg.setResultNote(Constants.PARAM_ERROR);
				peccMsg.getDetail().setPeccancyArray(null);
				peccMsg.setPages(0);
				peccMsg.setTotalRecordNum(0);
				return peccMsg;
			}
			List<Object> data = peccMsg.getDetail().getPeccancyArray()
					.subList(start, end);
			peccMsg.setPageNo(requestParams.getPageNo());
			int p = (totalRecord % requestParams.getPagesize()) == 0 ? 0 : 1;
			peccMsg.setPages(totalRecord / requestParams.getPagesize() + p);
			peccMsg.getDetail().setPeccancyArray(data);
		} catch (UnsupportedEncodingException e) {
			peccMsg.setResultNote(Constants.HTTP_ERROR);
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			logger.error(e);
			peccMsg.setResultNote(Constants.HTTP_ERROR);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error(e);
			peccMsg.setResultNote(Constants.HTTP_ERROR);
			e.printStackTrace();
		} finally {
			if (httpclient != null) {
				httpclient.getConnectionManager().shutdown();
				httpclient = null;
			}
		}
		return peccMsg;
	}
}
